<template>
  <FIModel v-model="visible" title="分配岗位" @close="closeClick" :showFotter="false">
    <el-row :gutter="20">
      <el-col :span="8">
        <FIFormItem prop="loginName" label="登录账号">
          <span>{{ editData.loginName }}</span>
        </FIFormItem>
      </el-col>
      <el-col :span="8">
        <FIFormItem prop="userName" label="用户姓名">
          <span>{{ editData.userName }}</span>
        </FIFormItem>
      </el-col>
      <el-col :span="8">
        <FIFormItem prop="deptCname" label="用户所属部门">
          <span>{{ editData.deptCname }}</span>
        </FIFormItem>
      </el-col>
    </el-row>

    <FITable
      ref="tableRef"
      class="box-radius2"
      title="用户岗位列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="dataList"
      primaryKey="formId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      insertable
      :showSaveModel="false"
      :settingConfig="settingConfig"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
    >
      <template #headerBtn>
        <FIButton id="savePostUsers" border style="margin-right: 10px" @click.stop="saveClick"></FIButton>
        <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          buttonText="删除"
          beforePopText="请选择一条数据"
          :btn-binds="{ id: 'deletePostUsers', border: true }"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn>
      </template>
      <template #partDepts="{ scope }">
        <FICascaderTree
          @select-data="selectData"
          :multiple="true"
          :showCheckbox="true"
          @select-node="selectNode($event, scope.$index)"
          id="orgId"
          :selectVal="scope.row.partDepts"
          :disabled="!scope.row.isSelected"
        ></FICascaderTree>
      </template>
      <template #postEname="{ scope }">
        <FISelect
          v-if="scope.row._isNew"
          v-model="scope.row.postEname"
          valueCustom="postEname"
          popperClass="select-postEname-class"
          :props="{ value: 'postEname', label: 'postEname' }"
          :options="postList"
          :display-key="['postEname', 'postCname']"
          @select="handleSelect($event, scope.$index)"
          remote
          :loadMoreEnd="loadMoreEnd"
          :remote-method="remoteMethod"
          clearable
          filterable
          usePagination
          @load-more="loadMore"
        />
        <span v-if="!scope.row._isNew">{{ scope.row.postEname }}</span>
      </template>
    </FITable>
  </FIModel>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, toRaw } from 'vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIForm from '@/components/FIForm.vue'
import FIModel from '@/components/FIModel.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { apiSavePostUsers, apiQueryUserPostsWithDept, apiUserquery, apiPostquery } from '@/api/user'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()
const emits = defineEmits(['close', 'update:postShow'])
const props = defineProps({
  // 圆角大小
  postShow: {
    type: Boolean,
    default: false,
  },
  editData: {
    type: Object,
    default: () => {
      return {}
    },
  },
})
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const register = reactive({
  userName: '',
  password: '',
  loginName: '',
  mobile: '',
  gender: '',
  email: '',
  businessPhone: '',
  jobNo: '',
  deptId: '',
})
const dataList = ref([])
const tableRef = ref(null)
const postList = ref([])

const userlistCurrent = ref(1)
const loadMoreEnd = ref(false)
const handleSelect = (item, index) => {
  tableRef.value.setCellValue(index, 'postCname', item.postCname)
  tableRef.value.setCellValue(index, 'postId', item.postId)
}
const selectNode = (data, index) => {
  let arr = []
  for (let i of data) {
    arr.push(i)
  }
  tableRef.value.setCellValue(index, 'partDepts', arr)
}

const getPostList = (loginName) => {
  const par = {
    loginName,
  }
  apiQueryUserPostsWithDept(par)
    .then((res) => {
      if (res.data.success) {
        dataList.value = res.data.data
        // pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.length)
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  // searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  // searchFn()
}
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  // let ids = []
  // Array.isArray(checkedRows.value) &&
  //   checkedRows.value.forEach((item: any) => {
  //     if (item?.postId) ids.push(item?.postId)
  //   })
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.postId) {
        ids.push({
          userId: props.editData.userId,
          postId: item.postId,
        })
      }
    })
  if (!ids.length) {
    // useMessage().warning('暂无数据')
    getPostList(props.editData.loginName)
    return
  }
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('deletePostUsers', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        getPostList(props.editData.loginName)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const isTableLoading = ref(false)
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 页面编码
const tableId = 'pageMaint'
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
})
const columns: Column[] = reactive([
  {
    label: '岗位编码',
    prop: 'postEname',
    align: 'center',
    queryName: '',
    modelValue: { inputValue: '' },
    editable: false,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    required: true,
    editConfig: {
      rules: { postEname: [{ required: true, message: '请选择岗位编码', trigger: 'change' }] },
    },
  },
  {
    label: '岗位名称',
    prop: 'postCname',
    align: 'center',
    queryName: '',
    editable: true,
    sortable: true,
    filterable: false,
    readonly: true,
  },
  {
    label: '是否所属部门任职',
    prop: 'selfdept',
    align: 'center',
    width: '200',
    queryName: '',
    filterable: false,
    editable: true,
    sortable: true,
    modelValue: [],
    editType: 'select',
    editConfig: {
      options: [
        { value: 1, label: '是' },
        { value: 0, label: '否' },
      ],
    },
  },
  {
    label: '兼职部门',
    prop: 'partDepts',
    align: 'center',
    editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    filterable: false,
    modelValue: { inputValue: '' },
    sortable: false,
    sortValue: '',
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
let visible: any = computed({
  get() {
    return props.postShow
  },
  set(val) {
    emits('update:postShow', val)
  },
})
const addRowSave = (data) => {
  handleSave(data, 'add')
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  // apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
  //   .then((res) => {
  //     isTableLoading.value = false
  //     if (res.data.success) {
  //       // saveSuccessful.value = true
  //       tableRef.value.clearSelection()
  //       searchFn()
  //     } else {
  //       ElMessage.error(res.data.message)
  //     }
  //   })
  //   .catch((error: any) => {
  //     isTableLoading.value = false
  //   })
}
const searchFn = (type?: string, columnsVal?: any, orgId?: any) => {
  // const obj = initSearchData(type, columnsVal, columns, state.query)
  // state.query = obj.queryData
  // columns.values = obj.columns
  // state.query.current = pageConfig.currentPage
  //   isTableLoading.value = true
  //   if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  // const par = {
  //   deptId:orgId || '',
  //   ...state.query,
  // }
  // apiUserquery(par)
  //   .then((res) => {
  //     isTableLoading.value = false
  //     if (res.data.success) {
  //       state.dataList = res.data.data.result
  //       pageConfig.pageSize = Number(res.data.data.size)
  //       pageConfig.total = Number(res.data.data.count)
  //     } else {
  //       // ElMessage.error(res.data.message)
  //     }
  //   })
  //   .catch((error: any) => {
  //     isTableLoading.value = false
  //     // 处理错误
  //   })
}
const closeClick = () => {
  visible.value = false
  emits('update:postShow', false)
}
const selectData = (val, name) => {
  // orgSelect.label = name
  register.deptId = val.value
}

const remoteMethod = (query) => {
  console.log(query, 'query')
  userlistCurrent.value = 1
  getPostSelect(query)
}
const loadMore = () => {
  if (loadMoreEnd.value && userlistCurrent.value > 1) return
  userlistCurrent.value++
  getPostSelect('')
}
const getPostSelect = (query) => {
  const par = {
    postAName: query || '',
    current: userlistCurrent.value,
    size: 10,
  }
  apiPostquery(par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        if (query) {
          postList.value = []
          postList.value = res.data.data.result
          return
        }
        postList.value = postList.value.concat(res.data.data.result)
        if (userlistCurrent.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const saveClick = () => {
  // for (let i of checkedRows.value) {
  //   if (!i.postEname) {
  //     useMessage().warning('请选择用户组编码')
  //     return
  //   }
  // }
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let par = checkedRows.value.map((item) => ({
    postId: item.postId,
    userId: props.editData.userId,
    selfdept: item.selfdept,
    partDepts: item.partDepts || [],
  }))
  const apiUrl = proxy.$Button_api('savePostUsers', route.name)
  apiRequestPost(apiUrl, par)
    .then((res) => {
      if (res.data.success) {
        getPostList(props.editData.loginName)
        useMessage().success(res.data.message)
        // emits('update:postShow', false)
      }
    })
    .catch((error: any) => {})
}
watch(
  () => props.postShow,
  (newValue) => {
    if (newValue) {
      getPostList(props.editData.loginName)
      getPostSelect()
    }
  }
)
</script>
<style lang="less" scoped></style>
